package com.ics.atable.chat.serializer;

import com.alibaba.cloud.ai.graph.OverAllState;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ics.atable.chat.model.dto.IntentExtract;
import com.ics.atable.chat.model.dto.KeyWordExtract;
import com.ics.atable.chat.model.dto.SynonymsExtract;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author haohongbin
 */
public class ItemQueryDeserializer extends JsonDeserializer<OverAllState> {


    private final ObjectMapper objectMapper;

    public ItemQueryDeserializer(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public OverAllState deserialize(JsonParser p, DeserializationContext context) throws IOException, JacksonException {

        ObjectNode node = objectMapper.readTree(p);

        Map<String, Object> data = objectMapper.convertValue(node.get("data"), new TypeReference<>() {
        });
        Map<String, Object> newData = new HashMap<>();

        // 处理 IntentExtract
        IntentExtract intentExtract = objectMapper.convertValue(data.get("intent_result"), IntentExtract.class);
        newData.put("intent", intentExtract);

        // 处理 KeyWordExtract
        KeyWordExtract keyWordExtract = objectMapper.convertValue(data.get("struct_token"), KeyWordExtract.class);
        newData.put("struct_token", keyWordExtract);

        // 处理 SynonymsExtract
        SynonymsExtract synonymsExtract = objectMapper.convertValue(data.get("synonyms"), SynonymsExtract.class);
        newData.put("synonyms", synonymsExtract);

        // 处理其他数据
        data.forEach((key, value) -> {
            if (!newData.containsKey(key)) {
                newData.put(key, value);
            }
        });

        return new OverAllState(newData);
    }
}
